<?php

namespace app\bll;

use app\validate\Datadict as ValidateDatadict;
use core\attribute\Template;
use Exception;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use support\Db;

/**
 * 数据字典
 */
class Datadict
{


    /**
     * 查找
     *
     * @param integer $id
     * @return array
     */
    #[Template]
    public function find(int $id, bool $jsondecode = true): array
    {
        $data =  Db::table('frame_datadict')
            ->where('id', '=', $id)
            ->first();
        if ($data !== null && $jsondecode) {
            $data = get_object_vars($data);
            $data['values'] = json_decode($data['values'], true);
        }
        return $data;
    }


    /**
     * 查询
     *
     * @return array
     */
    #[Template]
    public function select(int $status = 1): array
    {
        return  Db::table('frame_datadict')
            ->where('status', '=', $status)
            ->get()
            ->map(function ($value) {
                return (array)$value;
            })
            ->toArray();
    }

    /**
     * 添加字典
     *
     * @param array $data
     * @return integer
     */
    public function add(array $data): int
    {
        $ValidateDatadict = new ValidateDatadict();
        if (!$ValidateDatadict->check($data)) {
            throw new Exception($ValidateDatadict->getSimpleError());
        }

        $data['values'] = json_encode($data['values'], JSON_UNESCAPED_UNICODE);

        return  Db::table('frame_datadict')
            ->insertGetId($data);
    }


    /**
     * 编辑字段
     *
     * @param integer $id
     * @param array $data
     * @return void
     */
    public function edit(int $id, array $data)
    {
        $ValidateDatadict = new ValidateDatadict();
        if (!$ValidateDatadict->check($data)) {
            throw new Exception($ValidateDatadict->getSimpleError());
        }

        $data['values'] = json_encode($data['values'], JSON_UNESCAPED_UNICODE);

        return  Db::table('frame_datadict')
            ->where('id', '=', $id)
            ->update($data);
    }

    /**
     * 删除字典
     *
     * @param integer $id
     * @return integer
     */
    public function delete(int $id): int
    {

        return  Db::table('frame_datadict')
            ->where('id', '=', $id)
            ->update(['status' => -1]);
    }

    /**
     * 分页查询
     *
     * @param string $name
     * @param string $ident
     * @param integer $pagesize
     * @return LengthAwarePaginator
     */
    public function paginator(
        string $title = '',
        int $status = 1,
        int $pagesize = 20
    ): LengthAwarePaginator {
        return  Db::table('frame_datadict')
            ->when($title !== '', function ($query) use ($title) {
                return $query->where('title', 'like', '%' . $title . '%');
            })
            ->where('status', '=', $status)
            ->orderBy('id', 'desc')
            ->paginate($pagesize);
    }
}
